package com.tao.picture.ui.person.activity

import android.text.TextUtils
import androidx.lifecycle.lifecycleScope
import com.tao.BasicActivity
import com.tao.picture.base.data.PreferenceStore
import com.tao.picture.databinding.ActivityMainBinding
import com.tao.picture.ui.person.data.entity.User
import com.tao.util.ToastUtil
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import pub.devrel.easypermissions.EasyPermissions
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

/**
 * @AndroidEntryPoint 表示注解入口，用到hilt的组件都要加
 */
@AndroidEntryPoint
class PersonActivity : BasicActivity<ActivityMainBinding>() {

    @Inject
    lateinit var user: User // TestModule中的user

    @Inject
    lateinit var store: PreferenceStore

    // ViewBinding
    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    /**
     * 初始化视图
     */
    override fun initView() {
        // 返回键监听
        setBackPressed(binding.title)
    }

    override fun initData() {
        super.initData()
        // 获取上次开启时的时间
        getLastLoginTime()
        // 保存时间
        saveLastLoginTime()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        // 处理请求权限的结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    /**
     * 获取时间
     */
    private fun getLastLoginTime() {
        lifecycleScope.launch {
            val time = store.read()
            if (!TextUtils.isEmpty(time)) {
                ToastUtil.longToast("上次登录时间：$time")
            }
        }
    }

    // 保存时间
    private fun saveLastLoginTime() {
        lifecycleScope.launch {
            // withContext(Dispatchers.IO)会比getLastLoginTime先执行
            val time = SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss")
                .format(Date(System.currentTimeMillis()))
            store.save(time)
        }
    }
}

